<?php
#####################################################
#  COPYRIGHT NOTICE
#####################################################
# In the following statements, the term "this 
# program" refers to all files associated with the
# execution and distribution of Adtrackz.
#
# This Program is Copyright 2004 Jonah Klimack.
# All Rights Reserved. 
#
# Selling the code for this program, modifying 
# and/or redistributing the code for this program
# in part or in whole over the Internet or in any 
# other medium is expressly forbidden. Violators
# will be prosecuted to the fullest extent of the law
# Copyright and header information may not be
# modified.
#
# This program is distributed "as is" and without 
# warranty of any kind, either express or implied.
# In no event shall the liability of Jonah Klimack 
# for any damages, losses and/or causes of 
# action exceed the total amount paid by the 
# user for this software.		
#####################################################
# DO NOT MODIFY ANYTHING IN THIS FILE
#####################################################


header('P3P: CP="NOI DSP COR NID CUR OUR NOR"');
require "adtrackz_config.php";

//handle env variables
if ($_SERVER['HTTP_REFERER'])
	$referer = $_SERVER['HTTP_REFERER'];
else
	$referer = "none";
$time = time();

if ($cpc) //make it into a fraction
	$cpc /= 100; 

$cookiedomain = str_replace("www","",$domain);

//make lowercase
$c = strtolower($c);
$s = strtolower($s);

//strip & and | characters
$s = str_replace("&","",$s);
$s = str_replace("|","",$s);

if ($_COOKIE['ccampaign'])
{
	$all_ccampaigns = explode("|", $_COOKIE['ccampaign']);
	$all_ccampaigns = array_unique($all_ccampaigns); //remove duplicates 
}

if (!$c) //c is not defined
	record_alert('no campaign specified in go.php');
elseif (preg_match("/(\W+|\s+)/", $c, $matches)) //$c has illegal characters (sub can have them)
	record_alert("Adcode $c not in proper format. Campaign adcodes must contain letters,digits or an underscore character only.");
elseif ($c) // c is defined
{
	if (!$s) //no subcampaign, campaign is in cookie
	{
		//check if campaign is in cookie, ccampaign = cookie campaign
		if ($all_ccampaigns)
			$key = array_search($c,$all_ccampaigns);
		if ($key || $key === 0) //campaign repeat, 3 equal signs so it doesn't read 0 as false
		{
			list($campaignID,$purpose,$url) = mysql_fetch_row(mysql_query("select ID,purpose,url from adtrackz_campaigns where adcode='$c'"));

			if (!$campaignID) //if campaign isn't there, record error and exit
				record_alert("repeat visitor recorded for deleted campaign: $c");
			
			if ($u) 
				$url = $u; //u over-rides url from campaign, meaning, if u exists, then url is u

			//SET COOKIE
			unset ($all_ccampaigns[$key]); 	//set campaign in array to null and...
			$all_ccampaigns = array_values($all_ccampaigns); //automatically remove null elements
			$result = array_push($all_ccampaigns,$c); //pop encoded $c onto end
			$cvalue = implode("|",$all_ccampaigns);
			//echo "c defined and repeat, no su bcampaign, cookie=$cvalue <br>";
			$cvalue = prepare_cvalue($cvalue);
			setcookie("ccampaign",$cvalue,mktime (0,0,0,12,32,2010),"/",$cookiedomain);

			//RECORD CLICK
			mysql_query("insert into adtrackz_clicks values('','$campaignID','','$time','$referer','0','$cpc','$u');");	

			//SEND VISITOR TO URL
			go_url($url);
			exit;
		}
		else  //campaign unique
		{
			list($campaignID,$purpose,$url,$cost,$ppc) = mysql_fetch_row(mysql_query("select ID,purpose,url,cost,ppc from adtrackz_campaigns where adcode='$c'"));	

			if($ppc && !$cpc) //if no cpc is specified, and this is a ppc campaign
				$cpc = $cost; //then we have to insert the cpc into clicks
				//because in stats.php, ppc is calculated by adding all the clicks			
			
			if (!$campaignID) //if campaign doesn't exist, create campaign and set the three variables
			{			
				if ($cpc)
					$ppc = 1;
				$now_day = date("j");
				$now_month = date("n");
				$now_year = date("Y");
				$startdate = $now_year."-".$now_month."-".$now_day." 00:00:00";
				$enddate = "2004-12-31 00:00:00";
				if ($p == "all" || $p == "affiliate" || $p == "clicks" || $p == "actions" || $p == "sales") 
					$purpose = $p;					
				else
					$purpose = "all";
				if (!$u) //when creating a new campaign, u must be defined, if not, use default url
				{
					$default_url = mysql_fetch_row(mysql_query("select default_url from adtrackz_login"));
					$url = $default_url[0];
				}
				else //if u is defined when creating a new campaign, use u as campaign url
					$url = $u;
				mysql_query("insert into adtrackz_campaigns values('','0','$c','$url','$cpc','$startdate','$enddate','','$purpose','','','$ppc')");

				//get campaign ID
				$newcampaignID = mysql_fetch_row(mysql_query("select ID from adtrackz_campaigns where adcode='$c'"));
				$campaignID = $newcampaignID[0];

				//add split test option				
				mysql_query("insert into adtrackz_campaigns_st values ('$campaignID[0]', '')");
			}
			//over-riding variable is u
			if ($u) //if no campaing was created, this sets url to the proper value for go_url function
				$url = $u;

			//SET COOKIE
			if ($all_ccampaigns) //if we have a cookie with campaigns...
			{
				$result = array_push($all_ccampaigns,$c); //pop encoded $c onto end			
				$cvalue = implode("|",$all_ccampaigns);
			}
			else //just create a new cookie
				$cvalue = $c;
			//echo "c defined, unique campaign, no subcampaign, cookie=$cvalue <br>";
			$cvalue = prepare_cvalue($cvalue);
			setcookie("ccampaign",$cvalue,mktime (0,0,0,12,32,2010),"/",$cookiedomain);

			//RECORD CLICK
			mysql_query("insert into adtrackz_clicks values('','$campaignID','','$time','$referer','1','$cpc','$u');");	

			//SEND VISITOR TO URL
			go_url($url);
			exit;
		}
	}
	elseif ($s) //subcampaign is set
	{
		$campaign_sub_combo = $c."&".$s;
		if ($all_ccampaigns)
			$key = array_search($campaign_sub_combo,$all_ccampaigns);
		if ($key || $key === 0) //campaign&sub is a repeat (ie, sub is a repeat)
		{
			//global vars
			list($campaignID,$purpose,$url) = mysql_fetch_row(mysql_query("select ID,purpose,url from adtrackz_campaigns where adcode='$c'"));

			if (!$campaignID) //if campaign isn't there, record error and exit
				record_alert("repeat visitor recorded for deleted campaign: $c with subcampaign: $s");

			list($subID,$subUrl) = mysql_fetch_row(mysql_query("select ID,url from adtrackz_subcampaigns where adcode = '$s' && campaignID='$campaignID'"));			

			if (!$subID) //if subcampaign isn't there, record error and exit
				record_alert("repeat visitor recorded for deleted subcampaign: $s");

			//if u is defined, url is u, if not, since this is sub, url is the subUrl
			if ($u)
				$url = $u;
			elseif ($subUrl)
				$url = $subUrl;

			//SET COOKIE			
			unset ($all_ccampaigns[$key]); //set campaign in array to null and..
			$all_ccampaigns = array_values($all_ccampaigns); //automatically remove null elements
			$result = array_push($all_ccampaigns,$campaign_sub_combo); //pop it onto end
			$cvalue = implode("|",$all_ccampaigns);
			$cvalue = prepare_cvalue($cvalue);
			//echo "c defined, s defined, sub repeat cookie=$cvalue <br>";
			setcookie("ccampaign",$cvalue,mktime (0,0,0,12,32,2010),"/",$cookiedomain);

			//RECORD CLICK
			mysql_query("insert into adtrackz_clicks values('','$campaignID','$subID','$time','$referer','0','$cpc','$u');");	

			//SEND VISITOR TO URL
			go_url($url);
			exit;
		}
		else //campaign&sub (ie sub) is unique
		{
			//SET VARIABLES & CREATE DYNAMIC CAMPAIGNS OR SUBCAMPAIGNS
			list($campaignID,$purpose,$url, $cost, $ppc) = mysql_fetch_row(mysql_query("select ID,purpose,url,cost,ppc from adtrackz_campaigns where adcode='$c'"));

			if($ppc && !$cpc) //if no cpc is specified, and this is a ppc campaign
				$cpc = $cost; //then we have to insert the cpc into clicks
				//because in stats.php, ppc is calculated by adding all the clicks	

			if (!$campaignID) //if campaign isn't there, create campaign and sub
			{
				if ($cpc)
					$ppc = 1;
				$now_day = date("j");
				$now_month = date("n");
				$now_year = date("Y");
				$startdate = $now_year."-".$now_month."-".$now_day." 00:00:00";
				$enddate = "2004-12-31 00:00:00";
				if ($p == "all" || $p == "affiliate" || $p == "clicks" || $p == "actions" || $p == "sales") 
					$purpose = $p;					
				else
					$purpose = "all";
				if (!$u) //when creating a new campaign, u must be defined, if not, use default url
				{
					$default_url = mysql_fetch_row(mysql_query("select default_url from adtrackz_login"));
					$url = $default_url[0];
				}
				else
					$url = $u;
				mysql_query("insert into adtrackz_campaigns values('','0','$c','$url','$cpc','$startdate','$enddate','','$purpose','','','$ppc')");

				//get campaign ID
				$newcampaignID = mysql_fetch_row(mysql_query("select ID from adtrackz_campaigns where adcode='$c'"));
				$campaignID = $newcampaignID[0];

				//add split test option				
				mysql_query("insert into adtrackz_campaigns_st values ('$campaignID[0]', '')");

				//CREATE SUB				
				mysql_query("insert into adtrackz_subcampaigns values('','$campaignID','$s','$url','$cpc','','$ppc')");
				$newsubID = mysql_fetch_row(mysql_query("select ID from adtrackz_subcampaigns where adcode='$s' && campaignID='$campaignID'"));
				$subID = $newsubID[0];
			}
			else //campaign is found, see if sub isn't there
			{
				list($subID,$subUrl) = mysql_fetch_row(mysql_query("select ID,url from adtrackz_subcampaigns where adcode = '$s' && campaignID='$campaignID'"));			
				if (!$subID) //if subcampaign isn't there, record error and exit
				{
					if ($cpc)
						$ppc = 1;
					if ($u) //if u is defined
						$subUrl = $u;
					else //if campaign exists but sub doesn't, then subUrl = campaign url (not default url)
						$subUrl = $url;
					//CREATE SUB
					mysql_query("insert into adtrackz_subcampaigns values('','$campaignID','$s','$subUrl','$cpc','','$ppc')");
					$newsubID = mysql_fetch_row(mysql_query("select ID from adtrackz_subcampaigns where adcode='$s' && campaignID='$campaignID'"));
					$subID = $newsubID[0];
				}
				if ($u)
					$subUrl = $u;
			} 

			//in the above if statements, if campaign was found, we define subUrl
			if ($subUrl)
				$url = $subUrl;

			//SET COOKIE
			if ($all_ccampaigns) //if we have a cookie with campaigns...
			{
				$result = array_push($all_ccampaigns,$c."&".$s); //pop encoded $c onto end			
				$cvalue = implode("|",$all_ccampaigns);

			}
			else //just create a new cookie
				$cvalue = $c."&".$s;
			//echo "c defined, s defined, sub unique cookie=$cvalue <br>";			
			$cvalue = prepare_cvalue($cvalue);
			setcookie("ccampaign",$cvalue,mktime (0,0,0,12,32,2010),"/",$cookiedomain);

			//RECORD CLICK
			mysql_query("insert into adtrackz_clicks values('','$campaignID','$subID','$time','$referer','1','$cpc','$u');");	

			//SEND VISITOR TO URL
			go_url($url);
			exit;
		}

	}
}

function go_url($url)
{
	//at this point, what $url = has been worked out (taking into account $u, if $s is defined, etc)
	global $c,$s,$domain,$udirectory, $purpose;
	if ($purpose == "affiliate")
	{
		$a = "http://".$domain."/".$udirectory."/affsale.php";
		$a = urlencode($a);
		$url= urlencode($url);
		$afftrack = "http://adtrackz.com/afftrack.php?step=1&a=$a&url=$url&c=$c&s=$s";
		header("Location: $afftrack");
	}
	else				
	{
		//echo "$url";
		header("Location: $url");
	}
}


function record_alert($reason)
{
	global $c,$s,$referer;
	mysql_query("insert into adtrackz_alerts values ('','$c','$s',now(),'$referer','$reason');");
	$default_url = mysql_fetch_row(mysql_query("select default_url from adtrackz_login"));
	header("Location: $default_url[0]");
	exit;
}

//strips slashes from variable before setting cookie or the cookie will 
//add slashes, causing \\\\"keyword\\\"
function prepare_cvalue($cvalue)
{
	if (get_magic_quotes_gpc())
		return stripslashes($cvalue);
	else
		return $cvalue;
}


?>

